package com.example.infowall02.controller;

import com.example.infowall02.domain.CommentRequest;
import com.example.infowall02.domain.User;
import com.example.infowall02.mapper.ArticlesMapper;
import com.example.infowall02.mapper.UserMapper;
import com.example.infowall02.utils.Result;
import com.example.infowall02.utils.SensitiveWordFilter;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.infowall02.service.CommentService;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticlesMapper articlesMapper;
    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;

    // 添加评论
    @PostMapping
    public Result<CommentRequest> addComment(@RequestBody CommentRequest commentRequest) {

        int userId = commentRequest.getUserId();
        int articleId = commentRequest.getArticleId();
        // 检查用户是否存在
        int userCount = userMapper.countUserById(userId);
        if (userCount == 0) {
            return Result.error("用户不存在，评论失败");
        }
        // 检查文章是否存在
        int articleCount = articlesMapper.countArticleById(articleId);
        if (articleCount == 0) {
            return Result.error("文章不存在，评论失败");
        }
        // 设置评论时间
        commentRequest.setCreateTime(new Date());
        // 过滤敏感词
        String content = commentRequest.getContent();
        String filteredContent = sensitiveWordFilter.filter(content);
        commentRequest.setContent(filteredContent);
        // 用户和文章都存在，执行评论操作
        if (commentService.insertComment(commentRequest)) {
            // 评论成功，返回评论信息
            CommentRequest comment = commentService.findCommentById(commentRequest.getCommentId());
            return Result.success(comment);
        }
        return Result.error("评论失败");
    }

    // 删除评论
    @DeleteMapping("/{commentId}")
    public Result deleteComment(@PathVariable Integer commentId, HttpSession session) {
        // 检查当前session中是否存在登录用户信息或者管理员登录信息
        if (session.getAttribute("loggedInAdmin") != null || session.getAttribute("loggedInUserId") != null) {
            // 检查评论是否存在
            boolean isCommentExists = commentService.isCommentExists(commentId);
            if (isCommentExists) {
                if (session.getAttribute("loggedInAdmin") != null) {
                    // 管理员可以删除任何评论
                    commentService.deleteComment(commentId);
                    return Result.success("管理员删除评论成功");
                } else if (session.getAttribute("loggedInAdmin") == null
                        && session.getAttribute("loggedInUserId") != null) {
                    // 用户只能删除自己的评论
                    // 从session中获取用户id
                    Object userIdObj = session.getAttribute("loggedInUserId");
                    int userId = Integer.parseInt(userIdObj.toString());
                    // 检查评论是否属于当前用户
                    CommentRequest commentRequest = commentService.findCommentById(commentId);
                    if (commentRequest == null || commentRequest.getUserId() != userId) {
                        return Result.error("无法删除其他用户的评论");
                    }
                    commentService.deleteComment(commentId);
                    return Result.success("成功删除评论");
                } else {
                    return Result.error("无登录状态，无法删除评论");
                }
            }
            return Result.error("评论不存在，无法删除");
        }
        return Result.error("操作不合法，无法删除评论");
    }

    // 查询评论
    // 根据文章id查询评论
    @GetMapping("/byArticleId/{articleId}")
    public Result<List<Map<String, Object>>> findCommentsByArticleId(@PathVariable Integer articleId,
            @RequestParam int pageNow,
            @RequestParam int pageSize) {
        int totalCount = commentService.countCommentsByArticleId(articleId);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        // 确保总页数至少为 1
        totalPages = Math.max(totalPages, 1);
        // 确保起始索引不超过总记录数,并且不小于1
        pageNow = Math.max(pageNow, 1);
        pageNow = Math.min(pageNow, totalPages);
        // 计算起始索引
        pageNow = (pageNow - 1) * pageSize;

        // 调用服务层方法
        try {
            // 检查文章是否存在
            int articleCount = articlesMapper.countArticleById(articleId);
            if (articleCount == 0) {
                return Result.error("文章不存在，无法查询评论");
            }
            // 查询文章评论
            List<CommentRequest> comments = commentService.findCommentsByArticleId(articleId, pageNow, pageSize);
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (CommentRequest comment : comments) {
                // 为每个评论创建一个新的 Map
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("totalPages", totalPages);
                resultMap.put("comment", comment);
                User user = userMapper.getUserById(comment.getUserId());
                user.setPassword(null);
                resultMap.put("user", user);
                resultList.add(resultMap);
            }
            return Result.success(resultList);
        } catch (Exception e) {
            // 处理异常
            return Result.error("查询评论时出现错误：" + e.getMessage());
        }
    }

    // 根据评论id查询评论
    @GetMapping("/{commentId}")
    public Result<CommentRequest> findCommentById(@PathVariable Integer commentId) {
        CommentRequest commentRequest = commentService.findCommentById(commentId);
        if (commentRequest == null) {
            return Result.error("评论不存在，无法查询");
        }
        return Result.success(commentRequest);
    }

    // 修改评论
    @PutMapping("/{commentId}")
    public Result<CommentRequest> updateComment(@RequestBody CommentRequest commentRequest,
            @PathVariable Integer commentId,
            HttpSession session) {
        // 检查评论是否存在
        boolean isCommentExists = commentService.isCommentExists(commentId);
        if (!isCommentExists) {
            return Result.error("评论不存在，无法修改");
        }
        // 检查当前session中是否存在登录用户信息
        if (session.getAttribute("loggedInUserId") == null) {
            return Result.error("请先登录后再进行修改");
        }
        Object userIdObj = session.getAttribute("loggedInUserId");
        int userId = Integer.parseInt(userIdObj.toString());
        // 检查评论是否属于当前用户
        CommentRequest comment = commentService.findCommentById(commentId);
        if (comment.getUserId() == userId) {
            // 设置评论时间
            commentRequest.setCreateTime(new Date());
            // 过滤敏感词
            String content = commentRequest.getContent();
            String filteredContent = sensitiveWordFilter.filter(content);
            commentRequest.setContent(filteredContent);
            // 更新评论
            commentService.updateComment(commentRequest.getContent(), commentId, commentRequest.getCreateTime());
            CommentRequest updatedComment = commentService.findCommentById(commentId);
            return Result.success(updatedComment);
        }
        return Result.error("无法修改其他用户的评论");
    }
}
